package com.xy.controller;

import com.xy.redisson.RedissonLock;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 不基于注解方式锁操作
 *
 * @author xxy
 * @date 2022/1/6 12:50
 */
@RestController
@Slf4j
public class LockController {

    private final RedissonLock redissonLock;

    public LockController(RedissonLock redissonLock) {
        this.redissonLock = redissonLock;
    }

    /**
     * 模拟这个是商品库存
     */
    public static volatile Integer TOTAL = 10;


    @GetMapping("lock-decrease-stock")
    public String lockDecreaseStock() {
        String lockName = "lock";
        redissonLock.lock(lockName, 10L);
        try {
            if (TOTAL > 0) {
                TOTAL--;
            }
            Thread.sleep(50);
            log.info("===lock===减完库存后,当前库存===" + TOTAL);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //如果该线程还持有该锁，那么释放该锁。如果该线程不持有该锁，说明该线程的锁已到过期时间，自动释放锁
            if (redissonLock.isHeldByCurrentThread(lockName)) {
                redissonLock.unlock(lockName);
            }
        }
        return "==========================";
    }


    @GetMapping("try-lock-decrease-stock")
    public String tryLockDecreaseStock() {
        String lockName = "tryLock";
        if (redissonLock.tryLock(lockName, 10L, 20L)) {
            try {
                if (TOTAL > 0) {
                    TOTAL--;
                }
                Thread.sleep(50);
                log.info("====tryLock===减完库存后,当前库存===" + TOTAL);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                redissonLock.unlock(lockName);
            }
        } else {
            log.info("[ExecutorRedisson]获取锁失败");
        }
        return "=======================";
    }


}
